<template>
  <div class="parking-management-container">
    <!-- 页面标题和搜索区 -->
    <div class="page-header">
      <h2>车位管理</h2>
      <div class="header-actions">
        <a-input-search v-model:value="searchText" placeholder="搜索车位号" style="width: 250px" @search="onSearch" />
        <a-date-picker v-model:value="filterDate" placeholder="选择日期筛选" @change="handleDateChange" :allowClear="true"
          style="width: 180px" />
        <a-button type="primary" @click="showAddModal">
          <template #icon>
            <PlusOutlined />
          </template>
          新增车位
        </a-button>
      </div>
    </div>

    <!-- 车位表格 -->
    <a-table :columns="columns" :data-source="filteredParkingSpaces" :pagination="false" :loading="loading"
      :row-key="record => record.id"
      :row-class-name="record => record.id === selectedSpace?.id ? 'highlighted-row' : ''"
      @row-click="selectParkingSpace" bordered>
      <template #bodyCell="{ column, record }">
        <!-- 状态列 -->
        <template v-if="column.dataIndex === 'status'">
          <a-switch :checked="record.isActive" @change="checked => toggleStatus(record, checked)" size="small" />
          <a-tag :color="record.isActive ? 'green' : 'red'" style="margin-left: 8px">
            {{ record.isActive ? '启用' : '禁用' }}
          </a-tag>
        </template>

        <!-- 预约情况列 -->
        <template v-if="column.dataIndex === 'reservations'">
          <a-tag v-if="getReservationCount(record.id).upcoming > 0" color="blue">
            {{ getReservationCount(record.id).upcoming }} 个未来预约
          </a-tag>
          <a-tag v-if="getReservationCount(record.id).past > 0" color="gray">
            {{ getReservationCount(record.id).past }} 个历史预约
          </a-tag>
          <span v-if="getReservationCount(record.id).total === 0">无预约记录</span>
        </template>

        <!-- 操作列 -->
        <template v-if="column.dataIndex === 'actions'">
          <a-button type="link" size="small" @click.stop="selectParkingSpace(record)">
            <template #icon>
              <CalendarOutlined />
            </template>
            查看预约
          </a-button>
          <a-button type="link" size="small" @click.stop="showEditModal(record)">
            <template #icon>
              <EditOutlined />
            </template>
            编辑
          </a-button>
          <a-popconfirm title="确认删除此车位?" ok-text="确认" cancel-text="取消" @confirm="deleteParkingSpace(record)"
            @click.stop>
            <a-button type="link" danger size="small">
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 车位预约记录区域 -->
    <teleport to="body">
      <a-modal v-model:visible="historyModalVisible" title="车位预约记录" :footer="null" width="80vw" centered
        :mask-closable="true" class="history-modal">
        <div v-if="selectedSpace" class="history-section">
          <div class="history-header">
            <h3>车位 "{{ selectedSpace.spaceNumber }}" 预约记录</h3>
          </div>

          <!-- 简化历史记录筛选 -->
          <div class="history-filter">
            <div class="filter-group">
              <a-radio-group v-model:value="reservationTypeFilter" button-style="solid">
                <a-radio-button value="all">全部预约</a-radio-button>
                <a-radio-button value="upcoming">未来预约</a-radio-button>
                <a-radio-button value="past">历史预约</a-radio-button>
              </a-radio-group>

              <a-segmented 
                v-model:value="dateFilterType" 
                :options="[
                  { value: 'single', label: '单日筛选' },
                  { value: 'range', label: '时间段筛选' }
                ]"
                style="margin-left: 12px; margin-right: 8px;"
              />

              <a-date-picker 
                v-if="dateFilterType === 'single'"
                v-model:value="historyFilterDate" 
                placeholder="按日期筛选"
                style="width: 150px" 
                @change="handleHistoryDateChange" 
                :allowClear="true" 
              />

              <a-range-picker 
                v-else
                v-model:value="historyDateRange"
                :placeholder="['开始日期', '结束日期']"
                style="width: 250px"
                @change="handleHistoryDateRangeChange"
                :allowClear="true"
              />
            </div>

            <a-button type="primary" @click="exportData">
              <template #icon>
                <DownloadOutlined />
              </template>
              导出记录
            </a-button>
          </div>

          <!-- 预约记录表格 -->
          <a-table :columns="historyColumns" :data-source="filteredHistory" :pagination="false"
            :loading="historyLoading" bordered @row-click="viewReservationDetail" :row-class-name="'clickable-row'">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="getStatusColor(record.status)">
                  {{ getStatusText(record.status) }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </div>
      </a-modal>
    </teleport>

    <!-- 预约详情模态框 - 修复定位问题 -->
    <teleport to="body">
      <a-modal v-model:visible="detailModalVisible" title="预约详情" :footer="null" width="600px" centered
        :mask-closable="true" class="reservation-detail-modal">
        <div v-if="selectedReservation" class="reservation-detail">
          <div class="detail-header">
            <h3>车位 {{ selectedSpace?.spaceNumber }} 预约信息</h3>
            <a-tag :color="getStatusColor(selectedReservation.status)">
              {{ getStatusText(selectedReservation.status) }}
            </a-tag>
          </div>

          <a-descriptions bordered :column="1">
            <a-descriptions-item label="预约日期">
              {{ selectedReservation.date }}
            </a-descriptions-item>
            <a-descriptions-item label="时间段">
              {{ selectedReservation.timeSlot }}
            </a-descriptions-item>
            <a-descriptions-item label="员工姓名">
              {{ selectedReservation.employeeName }}
            </a-descriptions-item>
            <a-descriptions-item label="联系电话">
              <a :href="`tel:${selectedReservation.phone}`">
                {{ selectedReservation.phone }}
                <PhoneOutlined style="margin-left: 8px" />
              </a>
            </a-descriptions-item>
            <a-descriptions-item label="车牌号">
              {{ selectedReservation.plateNumber }}
            </a-descriptions-item>
            <a-descriptions-item label="预约时间">
              {{ selectedReservation.reservationTime }}
            </a-descriptions-item>
          </a-descriptions>

          <div class="detail-actions">
            <a-button @click="detailModalVisible = false">关闭</a-button>
            <a-button v-if="selectedReservation.status === 'pending' || selectedReservation.status === 'active'"
              type="danger" @click="cancelReservation">
              取消预约
            </a-button>
          </div>
        </div>
      </a-modal>
    </teleport>

    <!-- 新增车位对话框 -->
    <a-modal v-model:visible="addModalVisible" title="新增车位" @ok="handleAddSubmit" @cancel="resetForm"
      :confirm-loading="submitLoading">
      <a-form :model="formState" :rules="formRules" ref="formRef" layout="vertical">
        <a-form-item label="车位号" name="spaceNumber">
          <a-input v-model:value="formState.spaceNumber" placeholder="请输入车位号，如：101" />
        </a-form-item>
        <a-form-item label="状态" name="isActive">
          <a-switch v-model:checked="formState.isActive" />
          <span style="margin-left: 8px">{{ formState.isActive ? '启用' : '禁用' }}</span>
        </a-form-item>
        <a-form-item label="备注" name="note">
          <a-textarea v-model:value="formState.note" placeholder="可选填" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑车位对话框 -->
    <a-modal v-model:visible="editModalVisible" title="编辑车位" @ok="handleEditSubmit" @cancel="resetForm"
      :confirm-loading="submitLoading">
      <a-form :model="formState" :rules="formRules" ref="formRef" layout="vertical">
        <a-form-item label="车位号" name="spaceNumber">
          <a-input v-model:value="formState.spaceNumber" placeholder="请输入车位号，如：101" />
        </a-form-item>
        <a-form-item label="状态" name="isActive">
          <a-switch v-model:checked="formState.isActive" />
          <span style="margin-left: 8px">{{ formState.isActive ? '启用' : '禁用' }}</span>
        </a-form-item>
        <a-form-item label="备注" name="note">
          <a-textarea v-model:value="formState.note" placeholder="可选填" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import {
  PlusOutlined,
  DownloadOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  CloseOutlined,
  PhoneOutlined,
  CalendarOutlined,
  LeftOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { getParkingSpaceList, addParkingSpace, updateParkingSpace, getUserList } from '../api/index'; // 导入所需API
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

// 车位数据
const parkingSpaces = ref([]);
const loading = ref(true);
const searchText = ref('');

// 选中的车位
const selectedSpace = ref(null);

// 历史记录数据
const history = ref([]);
const historyLoading = ref(false);
const reservationTypeFilter = ref('all');

// 新增/编辑表单
const formRef = ref(null);
const formState = reactive({
  id: '',
  spaceNumber: '',
  isActive: true,
  note: ''
});

// 表单验证规则
const formRules = {
  spaceNumber: [
    { required: true, message: '请输入车位号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '车位号格式不正确', trigger: 'blur' }
  ]
};

// 对话框控制
const addModalVisible = ref(false);
const editModalVisible = ref(false);
const submitLoading = ref(false);

// 添加日期筛选状态
const filterDate = ref(null);

// 表格列定义
const columns = [
  {
    title: '车位号',
    dataIndex: 'spaceNumber',
    key: 'spaceNumber',
    sorter: (a, b) => a.spaceNumber.localeCompare(b.spaceNumber)
  },
  {
    title: '预约情况',
    dataIndex: 'reservations',
    key: 'reservations'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    filters: [
      { text: '启用', value: true },
      { text: '禁用', value: false }
    ],
    onFilter: (value, record) => record.isActive === value
  },
  {
    title: '操作',
    dataIndex: 'actions',
    key: 'actions'
  }
];

// 预约记录表格列定义
const historyColumns = ref([
  {
    title: '预约日期',
    dataIndex: 'date',
    key: 'date',
    sorter: (a, b) => new Date(a.date) - new Date(b.date)
  },
  //   { 
  //     title: '时段', 
  //     dataIndex: 'timeSlot', 
  //     key: 'timeSlot' 
  //   },
  {
    title: '员工姓名',
    dataIndex: 'employeeName',
    key: 'employeeName'
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '车牌号',
    dataIndex: 'plateNumber',
    key: 'plateNumber'
  },
  {
    title: '预约时间',
    dataIndex: 'reservationTime',
    key: 'reservationTime'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    filters: [
      { text: '进行中', value: 'active' },
      { text: '已完成', value: 'completed' },
      { text: '已取消', value: 'canceled' },
      { text: '待处理', value: 'pending' }
    ],
    onFilter: (value, record) => record.status === value,
  }
]);

// 根据筛选条件过滤车位
const filteredParkingSpaces = computed(() => {
  let result = parkingSpaces.value;

  // 关键字筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(item =>
      item.spaceNumber.toLowerCase().includes(keyword)
    );
  }

  // 日期筛选
  if (filterDate.value) {
    const selectedDate = filterDate.value.format('YYYY-MM-DD');

    // 筛选在指定日期有预约的车位
    result = result.filter(space => {
      const spaceReservations = getAllReservations().filter(res =>
        res.parkingSpaceId === space.id && res.date === selectedDate
      );
      return spaceReservations.length > 0;
    });
  }

  return result;
});

// 历史记录日期筛选
const historyFilterDate = ref(null);
const historyDateRange = ref([]);
const dateFilterType = ref('single'); // 'single' 或 'range'

const handleHistoryDateChange = (date) => {
  historyFilterDate.value = date;
  // 如果选择了单日期，清空日期范围
  if (date) {
    historyDateRange.value = [];
  }
};

const handleHistoryDateRangeChange = (dates) => {
  historyDateRange.value = dates;
  // 如果选择了日期范围，清空单日期
  if (dates && dates.length === 2) {
    historyFilterDate.value = null;
  }
};

// 修改历史记录筛选逻辑
const filteredHistory = computed(() => {
  let result = history.value;

  // 单日期筛选
  if (historyFilterDate.value) {
    const selectedDate = historyFilterDate.value.format('YYYY-MM-DD');
    result = result.filter(record => {
      // 如果日期包含时间部分，只取日期部分进行比较
      const recordDate = record.date.split(' ')[0];
      return recordDate === selectedDate;
    });
  }
  // 日期范围筛选
  else if (historyDateRange.value && historyDateRange.value.length === 2) {
    const startDate = historyDateRange.value[0].format('YYYY-MM-DD');
    const endDate = historyDateRange.value[1].format('YYYY-MM-DD');
    
    result = result.filter(record => {
      // 提取日期部分
      const recordDate = record.date.split(' ')[0];
      // 比较日期是否在范围内
      return recordDate >= startDate && recordDate <= endDate;
    });
  }

  // 根据预约类型筛选
  if (reservationTypeFilter.value === 'upcoming') {
    result = result.filter(item => {
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 设置为今天的开始时间
      
      // 处理日期格式，提取日期部分
      const dateStr = typeof item.date === 'string' ? item.date.split(' ')[0] : item.date;
      const itemDate = new Date(dateStr);
      return itemDate > today; // 今天之后的才算未来预约
    });
  } else if (reservationTypeFilter.value === 'past') {
    result = result.filter(item => {
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 设置为今天的开始时间
      
      // 处理日期格式，提取日期部分
      const dateStr = typeof item.date === 'string' ? item.date.split(' ')[0] : item.date;
      const itemDate = new Date(dateStr);
      return itemDate <= today; // 今天及以前的算历史预约
    });
  }

  return result;
});

// 搜索处理
const onSearch = (value) => {
  searchText.value = value;
};

// 获取车位的预约数量
const getReservationCount = (parkingId) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置为今天的开始时间
  const allReservations = getAllReservations().filter(res => res.parkingSpaceId === parkingId);

  // 今天之后的算未来预约
  const upcoming = allReservations.filter(res => {
    // 处理日期格式，提取日期部分
    const dateStr = typeof res.date === 'string' ? res.date.split(' ')[0] : res.date;
    const resDate = new Date(dateStr);
    return resDate > today;
  }).length;
  
  // 今天及以前的算历史预约
  const past = allReservations.filter(res => {
    // 处理日期格式，提取日期部分
    const dateStr = typeof res.date === 'string' ? res.date.split(' ')[0] : res.date;
    const resDate = new Date(dateStr);
    return resDate <= today;
  }).length;

  return {
    total: allReservations.length,
    upcoming,
    past
  };
};

// 显示新增对话框
const showAddModal = () => {
  resetForm();
  addModalVisible.value = true;
};

// 显示编辑对话框
const showEditModal = (record) => {
  resetForm();
  formState.id = record.id;
  formState.spaceNumber = record.spaceNumber;
  formState.isActive = record.isActive;
  formState.note = record.note || '';

  editModalVisible.value = true;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  formState.id = '';
  formState.spaceNumber = '';
  formState.isActive = true;
  formState.note = '';

  addModalVisible.value = false;
  editModalVisible.value = false;
  submitLoading.value = false;
};

// 提交新增表单
const handleAddSubmit = () => {
  formRef.value.validate().then(() => {
    submitLoading.value = true;

    // 准备请求参数
    const params = {
      space_number: formState.spaceNumber,
      status: formState.isActive ? 'active' : 'inactive',
      notes: formState.note || ''
    };

    // 调用添加车位API
    addParkingSpace(params)
      .then(response => {
        if (response && response.code === 200) {
          message.success(`车位 ${formState.spaceNumber} 添加成功`);
          
          // 关闭模态框并重置表单
          addModalVisible.value = false;
          resetForm();
          
          // 刷新车位列表
          fetchParkingSpaces();
        } else {
          message.error('添加车位失败：' + (response.message || '未知错误'));
          submitLoading.value = false;
        }
      })
      .catch(error => {
        console.error('添加车位出错:', error);
        message.error('添加车位失败，请检查网络连接');
        submitLoading.value = false;
      });
  }).catch(error => {
    console.log('表单验证失败:', error);
  });
};

// 提交编辑表单
const handleEditSubmit = () => {
  formRef.value.validate().then(() => {
    submitLoading.value = true;

    // 准备请求参数
    const params = {
      space_number: formState.spaceNumber,
      status: formState.isActive ? 'active' : 'inactive',
      notes: formState.note || ''
    };

    // 调用编辑车位API
    updateParkingSpace(formState.id, params)
      .then(response => {
        if (response && response.code === 200) {
          message.success(`车位 ${formState.spaceNumber} 更新成功`);
          
          // 关闭模态框并重置表单
          editModalVisible.value = false;
          resetForm();
          
          // 刷新车位列表
          fetchParkingSpaces();
          
          // 如果正在查看此车位的历史，更新选中的车位
          if (selectedSpace.value && selectedSpace.value.id === formState.id) {
            // 通过刷新后的列表数据查找最新的车位信息
            setTimeout(() => {
              const updatedSpace = parkingSpaces.value.find(item => item.id === formState.id);
              if (updatedSpace) {
                selectedSpace.value = updatedSpace;
              }
            }, 300);
          }
        } else {
          message.error('更新车位失败：' + (response.message || '未知错误'));
          submitLoading.value = false;
        }
      })
      .catch(error => {
        console.error('更新车位出错:', error);
        message.error('更新车位失败，请检查网络连接');
        submitLoading.value = false;
      });
  }).catch(error => {
    console.log('表单验证失败:', error);
  });
};

// 删除车位
const deleteParkingSpace = (record) => {
  // 模拟API请求
  setTimeout(() => {
    parkingSpaces.value = parkingSpaces.value.filter(item => item.id !== record.id);

    // 如果正在查看此车位的历史，清除选中状态
    if (selectedSpace.value && selectedSpace.value.id === record.id) {
      selectedSpace.value = null;
    }

    message.success(`车位 ${record.spaceNumber} 删除成功`);
  }, 300);
};

// 车位预约记录模态框
const historyModalVisible = ref(false);

// 选择车位并显示预约记录
const selectParkingSpace = (record) => {
  selectedSpace.value = record;
  historyModalVisible.value = true;

  // 加载该车位的预约记录
  fetchParkingHistory(record.id);
};

// 清除选择的车位
const clearSelection = () => {
  selectedSpace.value = null;
  historyModalVisible.value = false;
};

// 导出数据
const exportData = () => {
  if (!selectedSpace || filteredHistory.value.length === 0) {
    message.warning('没有可导出的预约记录');
    return;
  }

  try {
    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    
    // 格式化导出数据，增加空值检查
    const exportRecords = filteredHistory.value.map(record => {
      // 确保所有字段都有默认值，避免空值引用
      return {
        '预约日期': record.date || '',
        '时段': record.timeSlot || '全天',
        '员工姓名': record.employeeName || '未知',
        '联系电话': record.phone || '',
        '车牌号': record.plateNumber || '',
        '预约时间': record.reservationTime || '',
        '状态': getStatusText(record.status || 'unknown'),
        '消耗额度': (record.quotaConsumed !== undefined ? record.quotaConsumed : '0').toString()
      };
    });
    
    // 将数据转换为工作表
    const worksheet = XLSX.utils.json_to_sheet(exportRecords);
    
    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 预约日期列宽
      { wch: 15 }, // 时段列宽
      { wch: 12 }, // 员工姓名列宽
      { wch: 15 }, // 联系电话列宽
      { wch: 12 }, // 车牌号列宽
      { wch: 20 }, // 预约时间列宽
      { wch: 10 }, // 状态列宽
      { wch: 10 }  // 消耗额度列宽
    ];
    
    worksheet['!cols'] = colWidths;
    
    // 生成文件名，包含车位号和筛选日期信息
    // selectedSpace.spaceNumber
    let fileName = `车位${selectedSpace.value.spaceNumber || 'unknown'}_预约记录`;
    
    // 添加筛选类型信息
    if (reservationTypeFilter.value !== 'all') {
      fileName += `_${reservationTypeFilter.value === 'upcoming' ? '未来预约' : '历史预约'}`;
    }
    
    // 添加日期筛选信息 - 增加空值检查
    if (dateFilterType.value === 'single' && historyFilterDate.value) {
      fileName += `_${historyFilterDate.value.format('YYYY-MM-DD')}`;
    } else if (dateFilterType.value === 'range' && historyDateRange.value && historyDateRange.value.length === 2 && 
               historyDateRange.value[0] && historyDateRange.value[1]) {
      fileName += `_${historyDateRange.value[0].format('YYYY-MM-DD')}至${historyDateRange.value[1].format('YYYY-MM-DD')}`;
    }
    
    // 添加导出时间戳
    fileName += `_${new Date().toISOString().slice(0, 10)}`;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '预约记录');
    
    // 生成xlsx文件并下载
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    
    saveAs(blob, `${fileName}.xlsx`);
    
    message.success('预约记录导出成功');
  } catch (error) {
    console.error('导出错误:', error);
    message.error('导出失败，请重试');
  }
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    active: 'green',
    completed: 'blue',
    canceled: 'red',
    pending: 'orange'
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    active: '进行中',
    completed: '已完成',
    canceled: '已取消',
    pending: '待处理'
  };
  return textMap[status] || status;
};

// 所有预约数据 - 用于计算预约数量和全局筛选
const allReservations = ref([]);

// 用户数据 - 用于关联预约记录
const allUsers = ref([]);

// 在组件挂载时获取用户数据
const fetchAllUsers = () => {
  // 构建查询参数，获取最多1000个用户
  const params = {
    page: 1,
    per_page: 1000
  };
  
  // 调用API获取所有用户
  getUserList(params)
    .then(response => {
      if (response && response.code === 200 && response.data.data) {
        allUsers.value = response.data.data;
        console.log('已加载全量用户数据:', allUsers.value.length);
      } else {
        console.error('获取用户数据失败:', response.message || '未知错误');
        allUsers.value = [];
      }
    })
    .catch(error => {
      console.error('获取用户数据出错:', error);
      allUsers.value = [];
    });
};

// 根据用户ID查找用户信息
const findUserById = (userId) => {
  if (!userId || !allUsers.value.length) return null;
  return allUsers.value.find(user => user.id === userId);
};

// 获取所有预约数据 - 模拟API
const getAllReservations = () => {
  // 如果已有数据，直接返回
  if (allReservations.value.length > 0) {
    return allReservations.value;
  }

  // 模拟数据 - 包含未来预约和历史预约
  const today = new Date();
  const futureDate1 = new Date(today);
  futureDate1.setDate(today.getDate() + 5);
  const futureDate2 = new Date(today);
  futureDate2.setDate(today.getDate() + 10);

  const pastDate1 = new Date(today);
  pastDate1.setDate(today.getDate() - 5);
  const pastDate2 = new Date(today);
  pastDate2.setDate(today.getDate() - 10);

  const formatDate = (date) => {
    return date.toISOString().split('T')[0];
  };

  allReservations.value = [];

  return allReservations.value;
};

// 获取车位历史记录
const fetchParkingHistory = (spaceId) => {
  historyLoading.value = true;

  // 从全局预约数据中筛选当前车位的预约记录
  setTimeout(() => {
    // 先检查全局预约集合中是否有数据
    if (allReservations.value && allReservations.value.length > 0) {
      // 筛选出当前车位的预约
      const parkingReservations = allReservations.value.filter(
        res => res.parkingSpaceId === spaceId
      );
      console.log(parkingReservations);
      
      if (parkingReservations.length > 0) {
        // 如果有当前车位的预约数据，使用它们
        history.value = parkingReservations;
        message.success(`已加载 ${parkingReservations.length} 条预约记录`);
      } else {
        // 如果没有找到当前车位的预约记录
        history.value = [];
        message.info('该车位暂无预约记录');
      }
    } else {
      // 如果全局预约数据为空，使用模拟数据作为备选（仅开发环境使用）
      console.log('使用模拟预约数据');
      history.value = [];
      message.info('使用模拟预约数据展示');
    }
    
    historyLoading.value = false;
  }, 300);
};

// 获取车位数据
const fetchParkingSpaces = () => {
  loading.value = true;
  
  // 构建请求参数（如果有筛选条件）
  const params = {};
  if (searchText.value) {
    params.space_number = searchText.value;
  }
  
  // 调用API获取车位列表
  getParkingSpaceList(params)
    .then(response => {
      if (response && response.code === 200 && response.data.data) {
        // 使用API返回的数据，调整字段映射
        parkingSpaces.value = response.data.data.map(item => ({
          id: item.id.toString(),
          spaceNumber: item.space_number || '',
          isActive: item.status === 'active', // 根据status字段判断是否启用
          note: item.notes || '', // 使用notes字段作为备注
          // 保存原始预约数据，以便后续处理
          rawReservations: item.reservations || []
        }));
        
        // 处理预约数据
        if (parkingSpaces.value.length > 0) {
          // 将API返回的预约数据转换为前端使用的格式
          const allApiReservations = [];
          
          parkingSpaces.value.forEach(space => {
            if (space.rawReservations && space.rawReservations.length > 0) {
              const spaceReservations = space.rawReservations.map(res => {
                // 根据用户ID查找用户信息
                const user = findUserById(res.user_id);
                
                // 确保日期格式正确处理，只保留日期部分用于后续比较
                const reservationDate = res.reservation_date ? res.reservation_date.split(' ')[0] : '';
                
                return {
                  id: res.id.toString(),
                  parkingSpaceId: space.id,
                  userId: res.user_id,
                  date: reservationDate, // 使用处理后的日期
                  timeSlot: '全天', // API暂无时段信息，默认为全天
                  // 从用户信息中获取详细数据
                  employeeName: user ? user.name : '未知用户',
                  phone: user ? user.phone : '',
                  plateNumber: user ? user.license_plate : '',
                  reservationTime: res.reservation_date.split(' ')[0] || '',
                  status: res.status || 'active',
                  quotaConsumed: res.quota_consumed || 0
                };
              });
              
              allApiReservations.push(...spaceReservations);
            }
            
            // 删除临时字段，避免干扰其他功能
            delete space.rawReservations;
          });
          console.log(allApiReservations);
          // 如果有API返回的预约数据，使用它替换模拟数据
          if (allApiReservations.length > 0) {
            allReservations.value = allApiReservations;
          } else {
            // 否则初始化模拟预约数据
            getAllReservations();
          }
        } else {
          // 如果没有车位数据，初始化空的预约数组
          allReservations.value = [];
        }
        
        message.success('车位数据加载成功');
      } else {
        message.error('获取车位数据失败：' + (response.message || '未知错误'));
        // 加载失败时使用空数组
        parkingSpaces.value = [];
        allReservations.value = [];
      }
    })
    .catch(error => {
      console.error('获取车位数据出错:', error);
      message.error('获取车位数据失败，请检查网络连接');
      parkingSpaces.value = [];
      allReservations.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};

// 切换车位状态
const toggleStatus = (record, checked) => {
  const index = parkingSpaces.value.findIndex(item => item.id === record.id);
  if (index !== -1) {
    // 准备请求参数，只更新状态
    const params = {
      space_number: record.spaceNumber,
      status: checked ? 'active' : 'inactive',
      notes: record.note || ''
    };
    
    // 调用更新API
    updateParkingSpace(record.id, params)
      .then(response => {
        if (response && response.code === 200) {
          // 本地更新状态
          parkingSpaces.value[index].isActive = checked;
          
          // 显示成功消息
          message.success(`车位 ${record.spaceNumber} 已${checked ? '启用' : '禁用'}`);
          
          // 如果正在查看此车位的历史，更新选中的车位
          if (selectedSpace.value && selectedSpace.value.id === record.id) {
            selectedSpace.value = { ...parkingSpaces.value[index] };
          }
        } else {
          message.error('更新状态失败：' + (response.message || '未知错误'));
          // 恢复原始状态
          setTimeout(() => fetchParkingSpaces(), 300);
        }
      })
      .catch(error => {
        console.error('更新状态出错:', error);
        message.error('更新状态失败，请检查网络连接');
        // 恢复原始状态
        setTimeout(() => fetchParkingSpaces(), 300);
      });
  }
};

// 预约详情相关状态
const detailModalVisible = ref(false);
const selectedReservation = ref(null);

// 查看预约详情
const viewReservationDetail = (record) => {
  selectedReservation.value = record;
  detailModalVisible.value = true;

  // 确保模态框可见后进行重新计算位置
  setTimeout(() => {
    if (typeof document !== 'undefined') {
      const modalWrap = document.querySelector('.reservation-detail-modal');
      if (modalWrap) {
        modalWrap.style.display = 'flex';
        modalWrap.style.justifyContent = 'center';
        modalWrap.style.alignItems = 'center';
      }
    }
  }, 100);
};

// 取消预约
const cancelReservation = () => {
  if (!selectedReservation.value) return;

  // 在实际应用中，这里应该发送请求到服务器
  // 这里仅做模拟
  const recordId = selectedReservation.value.id;
  const index = history.value.findIndex(item => item.id === recordId);

  if (index !== -1) {
    history.value[index].status = 'canceled';

    // 全局预约列表也需要更新
    const allIndex = getAllReservations().findIndex(item => item.id === recordId);
    if (allIndex !== -1) {
      allReservations.value[allIndex].status = 'canceled';
    }

    message.success('预约已取消');
    detailModalVisible.value = false;
  }
};

// 日期变化处理
const handleDateChange = (date) => {
  filterDate.value = date;
  console.log('筛选日期:', date ? date.format('YYYY-MM-DD') : '全部');
};

// 组件加载时获取数据
onMounted(() => {
  // 先获取用户数据
  fetchAllUsers();
  // 然后获取车位数据
  fetchParkingSpaces();
});
</script>

<style scoped>
.parking-management-container {
  padding: 24px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.global-filter {
  display: none;
}

.history-section {
  margin-top: 24px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-filter {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
}

/* 高亮选中的行 */
:deep(.highlighted-row) {
  background-color: #e6f7ff;
}

/* 操作按钮间距 */
:deep(.ant-btn + .ant-btn) {
  margin-left: 8px;
}

/* 表格最大高度，避免太长 */
:deep(.ant-table-body) {
  max-height: 600px;
  overflow-y: auto;
}

/* 添加新样式 */
.clickable-row {
  cursor: pointer;
}

.clickable-row:hover {
  background-color: #f5f5f5;
}

.reservation-detail {
  padding: 0 16px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.detail-header h3 {
  margin: 0;
}

.detail-actions {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 修复模态框样式 */
:deep(.reservation-detail-modal) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  z-index: 1050 !important;
}

:deep(.ant-modal-mask) {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  z-index: 1000 !important;
}

:deep(.ant-modal-wrap) {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  z-index: 1000 !important;
  overflow: auto !important;
}

:deep(.ant-modal-content) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

:deep(.ant-modal-header) {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-modal-title) {
  font-weight: 600;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

/* 历史记录模态框样式 */
:deep(.history-modal) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  z-index: 1050 !important;
}

:deep(.history-modal .ant-modal-body) {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.history-section {
  padding: 0;
}

.history-header {
  margin-bottom: 24px;
}

.history-header h3 {
  margin: 0;
  font-size: 18px;
}

.history-filter {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>